<template>
    <div>
        <div>
            <div class="e-m-b-30">
                <el-radio-group v-model="way" size="mini" @change="searchDateField=1;getList()">
                    <el-radio-button label="0">出库中</el-radio-button>
                    <el-radio-button label="1">已出售</el-radio-button>
                </el-radio-group>
            </div>
            <!-- 更多筛选条件 -->
            <div class="other-search-form is-active">
                <el-form label-position="left" :inline="true" size="small">
                    <div class="flex align-items-center">
                        <!-- 时间筛选 -->
                        <timeChangeList v-model="timeType" @input="getList" @change="changeTime"></timeChangeList>
                    </div>
                    <div class="flex align-items-center">
                        <div class="e-flex-1" v-if="franchiseId == 0">
                            <el-form-item label="所属加盟商">
                                <franchiseList v-model="innerfranchiseid" :firstSelect="true" @change="selectFranchise"></franchiseList>
                            </el-form-item>
                        </div>
                        <div class="e-flex-1" v-if="innerfranchiseid > 0 && resetFilter">
                            <el-form-item label="出库站点">
                                <storeList v-model="innerstoreId" :franchiseId="innerfranchiseid" :multiple="true" @change="selectStore"></storeList>
                            </el-form-item>
                        </div>
                        <div class="e-flex-1" v-if="way == 1">
                            <el-form-item label="查询时间类型">
                                <el-select v-model="searchDateField" placeholder="选择时间类型" @change="getList(true)" clearable>
                                    <el-option label="创建时间" :value="0"></el-option>
                                    <el-option label="完结时间" :value="1"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </div>
                </el-form>
            </div>
            <div class="e-p-b-20">
                <el-button @click="downloadwithdrawa()" type="primary" plain><i class="iconfont icon-excel"></i>导出Excel</el-button>
            </div>
            <div class="admin-statistics-content">
                <div class="item e-flex-1">
                    <label>出库总重量</label>
                    <div class="e-m-t-10"><span class="num">{{ summary.weight }}</span><small>KG</small></div>
                </div>
                <div class="item e-flex-1">
                    <label>出库总件数</label>
                    <div class="e-m-t-10"><span class="num">{{ summary.quantity }}</span><small>件</small></div>
                </div>
                <div class="item e-flex-1">
                    <label>出库预估金额</label>
                    <div class="e-m-t-10"><span class="num">{{ summary.amount }}</span><small>元</small></div>
                </div>
                <div class="item e-flex-1" v-if="way == 1">
                    <label>销售总重量</label>
                    <div class="e-m-t-10"><span class="num">{{ summary.sellweight }}</span><small>KG</small></div>
                </div>
                <div class="item e-flex-1" v-if="way == 1">
                    <label>销售总件数</label>
                    <div class="e-m-t-10"><span class="num">{{ summary.sellquantity }}</span><small>件</small></div>
                </div>
                <div class="item e-flex-1" v-if="way == 1">
                    <label>销售总金额</label>
                    <div class="e-m-t-10"><span class="num">{{ summary.sellamount }}</span><small>元</small></div>
                </div>
            </div>
            <el-table ref="multipleTable" tooltip-effect="dark" :data="tableData" :span-method="objectSpanMethod" stripe
                border style="width: 100%; margin-top: 20px">
                <el-table-column label="品类" header-align="center">
                    <el-table-column prop="large" label="类型">
                    </el-table-column>
                    <el-table-column prop="name" label="可回收物">
                        <template slot-scope="scope">
                            <span>{{ scope.row.name }}</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="出库数量" header-align="center">
                    <el-table-column prop="number" label="出库数">
                        <template slot-scope="scope">
                            <span>{{ scope.row.number }}{{ scope.row.isweighing ? 'KG' : '件' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="小计">
                        <template slot-scope="scope">
                            <span v-if="scope.row.subtotalweight > 0" class="e-p-r-15">{{ scope.row.subtotalweight}}KG</span>
                            <span v-if="scope.row.subtotalquantity > 0">{{ scope.row.subtotalquantity}}件</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="出库预售" header-align="center">
                    <el-table-column prop="price" label="预售单价">
                        <template slot-scope="scope">
                            <span>{{ scope.row.price }}{{ scope.row.isweighing ? '元/KG' : '元/件' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="预售金额(元)">
                        <template slot-scope="scope">
                            <span>{{ scope.row.amount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="小计">
                        <template slot-scope="scope">
                            <span>{{scope.row.subtotalamount}}元</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="出库销售数量" header-align="center" v-if="way == 1">
                    <el-table-column prop="number" label="销售数">
                        <template slot-scope="scope">
                            <span>{{ scope.row.sellnumber }}{{ scope.row.isweighing ? 'KG' : '件' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="小计">
                        <template slot-scope="scope">
                            <span v-if="scope.row.subtotalsellweight > 0" class="e-p-r-15">{{ scope.row.subtotalsellweight}}KG</span>
                            <span v-if="scope.row.subtotalsellquantity > 0">{{ scope.row.subtotalsellquantity}}件</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="出库销售金额" header-align="center" v-if="way == 1">
                    <el-table-column prop="sellprice" label="销售均价">
                        <template slot-scope="scope">
                            <span>{{ scope.row.sellprice }}{{ scope.row.isweighing ? '元/KG' : '元/件' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sellamount" label="销售总金额(元)">
                        <template slot-scope="scope">
                            <span>{{ scope.row.sellamount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="小计">
                        <template slot-scope="scope">
                            <span>{{scope.row.subtotalsellamount}}元</span>
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
import timeChangeList from '@/components/form-select-type/timeChangeList.vue'
import storeList from '@/components/form-select-type/storeList.vue'
import franchiseList from '@/components/form-select-type/franchiseList.vue'
export default {
    props: {
        franchiseId: {
            type: Number,
            default: 0
        },
        storeId:{
            type: [Number, String],
            default: 0
        }
    },
    components: {
        timeChangeList,
        storeList,
        franchiseList
    },
    data() {
        return {
            way: 0, //状态(0.已出库，1.已完结)
            innerfranchiseid: null,
            dataType: 5,
            loading: false,
            tableData: [],
            innerstoreId: [],
            summary: {
                weight: 0,
                quantity: 0,
                amount: 0,
                sellquantity: 0, //售卖数量
                sellweight: 0, //售卖重量
                sellamount: 0, //售卖金额
            },
            resetFilter: true,
            // 时间类型
            timeType: 3, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
            startDate: '', //开始时间
            endDate: '', //结束时间
            searchDateField: 0, //搜索时间字段(0.创建时间，1.完结时间)
        };
    },
    watch: {
       
    },
    mounted() {
        if(this.franchiseId > 0){
            this.innerfranchiseid = this.franchiseId
        }
        if(this.storeId > 0){
            this.innerstoreId = [this.storeId]
        }
        this.getList()
    },
    methods: {
        objectSpanMethod({
            row,
            column,
            rowIndex,
            columnIndex
        }) {
            if (columnIndex < 1 || column.label === '小计') {
                const currentLarge = row.large;
                // 只有在组内第一行才返回合并行数，其余行返回[0,0]
                if (rowIndex === 0 || this.tableData[rowIndex - 1].large !== currentLarge) {
                    // 计算从当前行开始，连续相同large的行数
                    let rowspan = 1;
                    for (let i = rowIndex + 1; i < this.tableData.length; i++) {
                        if (this.tableData[i].large === currentLarge) {
                            rowspan++;
                        } else {
                            break;
                        }
                    }
                    return [rowspan, 1];
                } else {
                    return [0, 0];
                }
            }
            return [1, 1]; // 其他列不合并
        },
        flattenData(data, level = 0, parentPath = []) {
            let result = [];
            data.forEach(item => {
                const currentPath = [...parentPath, item];
                item.product.forEach(product => {
                    result.push({
                        id: product.id,
                        name: product.name,
                        weight: product.weight,
                        quantity: product.quantity,
                        amount: product.amount,
                        price: product.price,
                        sellamount: product.sellamount,
                        sellprice: product.sellprice,
                        sellquantity: product.sellquantity,
                        sellweight: product.sellweight,
                        subtotalweight: item.weight,
                        subtotalquantity: item.quantity,
                        subtotalamount: item.amount,
                        subtotalsellweight: item.sellweight,
                        subtotalsellquantity: item.sellquantity,
                        subtotalsellamount: item.sellamount,
                        isweighing: product.isweighing,
                        number: product.isweighing?product.weight:product.quantity,
                        sellnumber: product.isweighing?product.sellweight:product.sellquantity,
                        large: item.name,
                        bigid: item.id,
                        level: level,
                        isCategory: true,
                    });
                })
                // 递归处理子类型
                if (item.type && item.type.length > 0) {
                    // console.log(currentPath)
                    const childData = this.flattenData(item.type, level + 1, currentPath);
                    console.log('递归处理子类型-childData:', childData)
                    childData.forEach((cell) => {
                        result = result.concat([{
                            id: cell.id,
                            name: cell.name,
                            isweighing: cell.isweighing,
                            weight: cell.weight,
                            quantity: cell.quantity,
                            amount: cell.amount,
                            price: cell.price,
                            sellamount: cell.sellamount,
                            sellprice: cell.sellprice,
                            sellquantity: cell.sellquantity,
                            sellweight: cell.sellweight,
                            number: cell.isweighing?cell.weight:cell.quantity,
                            sellnumber: cell.isweighing?cell.sellweight:cell.sellquantity,
                            large: currentPath[0].name,
                            bigid: currentPath[0].id,
                            level: cell.level,
                            isCategory: cell.isCategory,
                        }]);
                    })

                }
            })
            return result;
        },
        getList() {
            this.tableData = []
            let params = {
                timeType: this.timeType,
                startDate: this.startDate,
                endDate: this.endDate,
                state: this.way,
                searchDateField: this.searchDateField,
                storeId: this.innerstoreId || 0,
                franchiseId: this.innerfranchiseid || 0,
                isFilterZero: true
            }
            return this.$axios.post(`/Statistics/StoreSell`, params).then(res => {
                this.tableData = this.flattenData(res.type)
                this.summary.weight = res.weight
                this.summary.quantity = res.quantity
                this.summary.amount = res.amount
                this.summary.sellweight = res.sellweight
                this.summary.sellquantity = res.sellquantity
                this.summary.sellamount = res.sellamount
                console.log(this.tableData)
                this.loading = false

            })
        },
        downloadwithdrawa() {
            let params = {
                timeType: this.timeType,
                startDate: this.startDate,
                endDate: this.endDate,
                state: this.way,
                searchDateField: this.searchDateField,
                storeId: this.innerstoreId || 0,
                franchiseId: this.innerfranchiseid || 0,
                isFilterZero: true
            }
            this.$axios.post('/Statistics/StoreSell/Download', params, {
                responseType: 'blob'
            }).then(res => {
                console.log(res)
                let content = res;
                let fileName = '出库销售表.xls'
                this.utils.saveAndExport(content, fileName)
            })
        },
        // 选择时间
        changeTime(e) {
            console.log(e)
            this.startDate = e['startDate']
            this.endDate = e['endDate']
            this.timeType = e['timeType']
            this.getList()
        },
        // 选择站点
        selectStore(value) {
            this.innerstoreId = value,
            this.getList(true)
        },
        // 选择加盟商
        selectFranchise(value){
            this.resetFilter = false
            this.innerfranchiseid = value
            this.innerstoreId = []
            this.getList(true).finally(() => {
                this.resetFilter = true
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.admin-statistics-content {
    display: flex;
    background-color: #fff;
    padding: 15px;
    height: calc(100% - 30px);
    border: 1px solid var(--light);

    .item {
        &+.item {
            border-left: 1px solid var(--light);
            padding-left: 30px;
        }

        .icon {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            border: 1px solid var(--light);
            background-color: #f2f3f5;
            padding: 5px;
            margin: 0 20px 0 0;
            box-shadow: 3px 2px 11px 0 rgb(70 70 70 / 22%);
        }

        label {
            color: var(--grey);
            font-size: 12px;
            margin-bottom: 5px;
            display: block;
        }

        .num {
            font-size: 30px;
        }
    }
}
</style>